<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="company-box box-card">
        <!-- 标签页 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 新增按钮 -->
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="editRoleDialog = true">新增角色</el-button>
            <!-- table表格 -->
            <el-table
              border
              :data="roles"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="150"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
                sortable
              />
              <el-table-column
                prop="description"
                label="描述"
                sortable
              />
              <el-table-column
                prop="address"
                label="操作"
                width="250"
                align="center"
              >
                <template v-slot="{ row }">
                  <el-button size="mini" type="text" @click="onSetPermission(row)">分配权限</el-button>
                  <el-button size="mini" type="text" @click="onEditRoles(row)">修改</el-button>
                  <el-button size="mini" type="text" @click="onDelRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="info">公司信息</el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 修改角色对话框 -->
    <!-- 组件内部 dialog组件关闭的时候 -->
    <!-- 1. 修改editRoleDialog -->
    <!-- 2. 告诉组件外界dialog关闭了 this.$emit('close') -->
    <el-dialog
      :title="titleText"
      :visible.sync="editRoleDialog"
      width="30%"
      @close="onDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="setPermissionTitle"
      :visible.sync="setPermissionDialog"
      width="50%"
      @close="onClose"
    >
      <el-tree v-if="setPermissionDialog" ref="setPermissionTree" node-key="id" :check-strictly="true" :default-checked-keys="defaultKeys" :data="permissionList" :props="defaultProps" show-checkbox default-expand-all />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setPermissionDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSetPermissionSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, delRole, getRoleById, updateRole } from '@/api/company.js'
import { getPerssionList, setPermissionToRole } from '@/api/permission.js'
import { transListToTree } from '@/utils'
export default {
  name: 'Settings',
  data() {
    return {
      activeName: 'role', // 控制默认选中
      roles: [],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      editRoleDialog: false,
      // 编辑和新增表单数据
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      setPermissionDialog: false,
      setPermissionTitle: '',
      permissionList: [],
      defaultProps: {
        // 控制显示哪个数据字段
        label: 'name'
      },
      defaultKeys: [], // 树默认选中
      roleId: ''
    }
  },

  computed: {
    titleText() {
      return (this.form.id ? '编辑' : '新增') + '角色'
    }
  },

  created() {
    this.loadRoleList()
  },

  methods: {
    // 加载角色列表
    async loadRoleList() {
      const res = await getRoleList(this.page)
      this.roles = res.rows
      this.total = res.total
    },
    // 当前页发生变化
    handleCurrentChange(val) {
      // console.log(val)
      this.page.page = val
      this.loadRoleList()
    },
    // 点击删除
    onDelRoles(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(id)
        this.$message.success('删除成功')
        this.loadRoleList()
      }).catch(() => {})
    },
    // 点击编辑
    async onEditRoles(row) {
      const res = await getRoleById(row.id)
      this.form = res
      this.editRoleDialog = true
    },
    // 点击了确定
    async onSave() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 编辑
          await updateRole(this.form)
        } else {
          // 新增
          console.log('新增')
        }
        this.editRoleDialog = false
        this.$message.success('更新成功')
        this.loadRoleList()
      } catch (err) { console.log(err) }
    },
    // 监听对话框关闭
    onDialogClose() {
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 点击分配权限
    async onSetPermission(row) {
      this.roleId = row.id
      this.setPermissionTitle = '为[' + row.name + ']分配权限'
      this.setPermissionDialog = true
      // 获取所有的权限
      this.permissionList = transListToTree('0', await getPerssionList())
      // 获取当前角色所拥有的权限
      this.defaultKeys = (await getRoleById(row.id)).permIds
    },
    // 点击分配权限保存
    async onSetPermissionSave() {
      const permissionIds = this.$refs.setPermissionTree.getCheckedKeys()
      if (!permissionIds.length) return this.$message.error('请选择必要的权限')
      await setPermissionToRole({
        id: this.roleId,
        permIds: permissionIds
      })
      this.$message.success('分配成功')
      this.setPermissionDialog = false
    },
    onClose() {
      this.defaultKeys = []
    }
  }
}
</script>

<style scoped lang='scss'>
.company-box {
  ::v-deep.el-tabs__item {
    font-size: 18px;
    padding: 0 40px;
    width: 150px;
    text-align: center;
  }

  .el-pagination {
    display: flex;
    justify-content: flex-end;
  }
}
::v-deep .el-tree-node__expand-icon{
    display: none !important;
  }
</style>
